﻿using System;
using System.Linq.Expressions;
using System.Reflection;

namespace MyFramework.Command.DelegateWatchCommand
{
    /// <summary>
    /// property selector util
    /// </summary>
    public static class PropertySelectorUtils
    {

        /// <summary>
        /// Gets the name of the property.
        /// </summary>
        /// <param name="propSelector">The prop selector.</param>
        /// <returns></returns>
        public static string GetPropertyName(LambdaExpression propSelector)
        {
            return GetProperty(propSelector).Name;
        }

        /// <summary>
        /// Gets the property.
        /// </summary>
        /// <param name="propSelector">The prop selector.</param>
        /// <returns></returns>
        public static PropertyInfo GetProperty(LambdaExpression propSelector)
        {
            var body = propSelector.Body;
            var prms = propSelector.Parameters;
            if (prms.Count != 1)
            {
                throw new ArgumentException("Property accessor must have exactly one argument.");
            }
            if (body.NodeType == ExpressionType.Convert)
            {
                body = ((UnaryExpression)body).Operand;
            }
            if (body.NodeType != ExpressionType.MemberAccess)
            {
                throw new ArgumentException("Lambda expression is not a property accessor");
            }
            MemberExpression mex = (MemberExpression)body;
            return mex.Member as PropertyInfo;
        }
    }
}
